//
//  HMSportTracking.m
//  XRSport
//
//  Created by acer on 16/10/21.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "HMSportTracking.h"
NSString *const HMSportNotificationGPSSignal = @"HMSportNotificationGPSSignal";
@implementation HMSportTracking
{
    //起点位置
    CLLocation *_startLocation;
    //所有运动模型的数据
    NSMutableArray<HMSportTrackingLine *> *_trackingLines;
    //gps之前定位的点
    CLLocation *_gpsPreLocation;

    
}
-(void)postNotificationWithState:(HMSPortGPSSignal)state
{
    [[NSNotificationCenter defaultCenter] postNotificationName:HMSportNotificationGPSSignal object:@(state)];
}
-(HMSPortGPSSignal)gpsSignalWithLocation:(CLLocation *)location
{
    HMSPortGPSSignal state = HMSPortGPSSignalNormal;
    if (location.speed < 0) {
        [self postNotificationWithState:state];
        return state;
    }
    if (_gpsPreLocation == nil) {
        _gpsPreLocation = location;
        [self postNotificationWithState:state];
        return state;
    }
    NSTimeInterval delta = ABS([location.timestamp timeIntervalSinceDate:_gpsPreLocation.timestamp]);
//    NSLog(@"%f",delta);
    delta = ABS(delta - 1);
    if (delta < 0.01) {
        state = HMSPortGPSSignalGood;
    } else if (delta < 1){
        state = HMSPortGPSSignalNormal;
    }
    [self postNotificationWithState:state];
    _gpsPreLocation = location;
    return state;
}
- (instancetype)initWithSportType:(HMSportType)sportType sportState:(HMSportState)sportState
{
    if (self = [super init]) {
        _sportType = sportType;
        _sportState = sportState;
        _trackingLines = [NSMutableArray array];
    }
    return self;
}
-(UIImage *)sportImage
{
    UIImage *image;
    switch (_sportType) {
        case HMSportTypeRun:
            image = [UIImage imageNamed:@"map_annotation_run"];
            break;
        case HMSportTypeWalk:
            image = [UIImage imageNamed:@"map_annotation_walk"];
            break;
        case HMSportTypeRide:
            image = [UIImage imageNamed:@"map_annotation_bike"];
            break;
            
        default:
            break;
    }
    return image;
}
-(MAPolyline *)appendLocation:(CLLocation *)location
{
    if ([self gpsSignalWithLocation:location] < HMSPortGPSSignalNormal) {
        return nil;
    }
    [self checkSportStateWithLocation:location];
    if (_sportState != HMSportStateContinue) {
        return nil;
    }
    // 0. 判断速度是否发生变化 - 性能优化，室内定位，速度有可能为`负数`
//    if (location.speed <= 0) {
//        return nil;
//    }
    // 将定位时间和当前时间做比较，如果差值过大，说明 GPS 信号不好（室内／初始定位)
    // 目的：性能优化，减少不必要的数据点，减少杂线！
//    if ([[NSDate date] timeIntervalSinceDate:location.timestamp] > 2) {
//        return  nil;
//    }
    if (_startLocation == nil) {
        _startLocation = location;
        return nil;
    }
    
    HMSportTrackingLine *trackingLine = [[HMSportTrackingLine alloc]initWithStartP:_startLocation endP:location];
    [_trackingLines addObject:trackingLine];
//    NSLog(@"%lf,%lf,%lf,%lf",self.avgSpeed,self.maxSpeed,self.totalDistance,self.totalTime);
    _startLocation = location;
    return trackingLine.polyline;
}
-(void)checkSportStateWithLocation:(CLLocation *)location
{
    if (_startLocation == nil) {
        return;
    }
    if (location.speed == 0 && _sportState == HMSportStateContinue) {
        
        _sportState = HMSportStatePause;
    }
    if (location.speed > 0 && _sportState == HMSportStatePause) {
        _sportState = HMSportStateContinue;
    }
}
-(double)avgSpeed
{
    return [[_trackingLines valueForKeyPath:@"@avg.speed"] doubleValue];
}
-(double)maxSpeed
{
    return [[_trackingLines valueForKeyPath:@"@max.speed"] doubleValue];
}
-(double)totalTime
{
    return [[_trackingLines valueForKeyPath:@"@sum.time"] doubleValue];
}
-(double)totalDistance
{
    return [[_trackingLines valueForKeyPath:@"@sum.distance"] doubleValue];
}
-(CLLocation *)startSportLocation
{
    return _trackingLines.firstObject.startLocation;
}
-(NSString *)totalTimeStr
{
    NSUInteger hh = (NSUInteger)self.totalTime / 3600;
    NSUInteger mm = (NSUInteger)self.totalTime % 3600 / 60;
    NSUInteger ss = (NSUInteger)self.totalTime % 60;
    return [NSString stringWithFormat:@"%02zd:%02zd:%02zd",hh,mm,ss];
}
-(void)setSportState:(HMSportState)sportState
{
    _sportState = sportState;
    if (_sportState != HMSportStateContinue) {
        _startLocation = nil;
    }
}
@end
